﻿using System;
using System.Collections.Generic;
using System.Net.Sockets;

namespace P2P.Network.SocketServer
{
    public class BufferPool
    {
        Int32 totalBytes;
        Byte[] buffer;
        Stack<Int32> freeIndexPool;
        Int32 currentIndex;
        Int32 bufferSize;

        public BufferPool(Int32 numberOfBuffers, Int32 bufferSize)
        {
            this.totalBytes = numberOfBuffers * bufferSize;
            this.bufferSize = bufferSize;

            currentIndex = 0;
            freeIndexPool = new Stack<Int32>();
            buffer = new Byte[totalBytes];
        }

        public void CheckOut(SocketAsyncEventArgs args)
        {
            lock (freeIndexPool)
            {
                if (freeIndexPool.Count > 0)
                    args.SetBuffer(buffer, freeIndexPool.Pop(), bufferSize);
                else
                {
                    args.SetBuffer(buffer, currentIndex, bufferSize);
                    currentIndex += bufferSize;
                }
            }
        }

        public void CheckIn(SocketAsyncEventArgs args)
        {
            lock (freeIndexPool)
            {
                freeIndexPool.Push(args.Offset);
                args.SetBuffer(null, 0, 0);
            }
        }

        public int Available
        {
            get
            {
                lock (freeIndexPool)
                { 
                    return ((totalBytes - currentIndex) / bufferSize) + freeIndexPool.Count; 
                }
            }
        }
    }
}
